package com.lmabbe.oauth.config;

import com.lmabbe.oauth.filter.JwtAuthenticationFilter;
import com.lmabbe.oauth.granter.authentication.SmsVerificationCodeAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author lmabbe
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Qualifier("userDetailServiceImpl")
    @Autowired
    private UserDetailsService userDetailsServiceImpl;

    @Autowired
    private AuthenticationManagerBuilder authenticationManagerBuilder;


    /**
     * 使用 Spring Security 推荐的加密方式进行登录密码的加密
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    /**
     * 用于通过允许轻松添加AuthenticationProviders来建立身份验证机制：以下内容使用内置的“用户”和“管理员”登录来定义内存中身份验证。
     * void configure(AuthenticationManagerBuilder auth) {
     * auth
     * .inMemoryAuthentication()
     * .withUser("user")
     * .password("password")
     * .roles("USER")
     * .and()
     * .withUser("admin")
     * .password("password")
     * .roles("ADMIN","USER");
     * }
     */
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(bCryptPasswordEncoder());
        daoAuthenticationProvider.setUserDetailsService(userDetailsServiceImpl);
        daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
        auth.authenticationProvider(daoAuthenticationProvider);
        auth.authenticationProvider(smsVerificationCodeAuthenticationProvider());

        //注册进authenticationProvider ，要不然使用自定义 grant_type 会报错
        authenticationManagerBuilder.authenticationProvider(daoAuthenticationProvider);
        authenticationManagerBuilder.authenticationProvider(smsVerificationCodeAuthenticationProvider());
    }


    /**
     * configure（WebSecurity）用于影响全局安全性的配置设置（忽略资源，设置调试模式，通过实现自定义防火墙定义拒绝请求）。
     * 例如，以下方法将导致以/ resources /开头的任何请求被忽略以进行身份验证。
     * protected void configure(HttpSecurity http) throws Exception {
     * http
     * .authorizeRequests()
     * .antMatchers("/admin/**").hasRole("ADMIN")
     * .anyRequest().authenticated()
     * }
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    /**
     * configure（HttpSecurity）允许基于选择匹配在资源级别配置基于Web的安全性
     * 例如以下示例将以/ admin /开头的URL限制为具有ADMIN角色的用户，并声明需要成功验证任何其他URL。
     * public void configure(WebSecurity web) throws Exception {
     * web
     * .ignoring()
     * .antMatchers("/resources/**");
     * }
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.cors();

        http.csrf().disable();

        // 指定未登录入口点
        http.exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint());
        //登录设置
        http.formLogin()
                .loginProcessingUrl("/common/login")
                .failureForwardUrl("/")
                .successForwardUrl("/");

        //登出设置
        http.logout()
                .logoutUrl("/common/logout")
                .clearAuthentication(true)
                .logoutSuccessHandler((request, response, authentication) -> {
                    System.out.println("success");
                });

        //session设置
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        //请求设置
        http.authorizeRequests()
                .antMatchers("/oauth/**").permitAll()
                .antMatchers("/common/login").permitAll()
                .antMatchers("/captcha/**").permitAll()
                .anyRequest().authenticated();

        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    public SmsVerificationCodeAuthenticationProvider smsVerificationCodeAuthenticationProvider() {
        SmsVerificationCodeAuthenticationProvider smsVerificationCodeAuthenticationProvider = new SmsVerificationCodeAuthenticationProvider();
        smsVerificationCodeAuthenticationProvider.setUserDetailsService(userDetailsServiceImpl);
        return smsVerificationCodeAuthenticationProvider;
    }
}
